package com.youpai.platform.vulture.service.handler.event;

import com.youpai.platform.chat.service.entity.dto.OfflineEventDTO;
import com.youpai.platform.chat.service.service.VultureChatEventFacadeInterface;
import com.youpai.platform.common.exceptions.RemoteException;
import com.youpai.platform.vulture.service.channel.ChannelAttrs;
import com.youpai.platform.vulture.service.channel.VultureChannel;
import com.youpai.platform.vulture.service.handler.vulture.ConnectHandler;
import com.youpai.platform.vulture.service.support.VultureChannelSupport;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @date: 2022/7/10 22:42
 * @author: Anna
 * @version: 1.0
 * @description: 关闭vulture通道处理
 */
@Slf4j
@Component
public class DisConnectedVultureChannelMessageHandler implements ConnectHandler {

    @Resource
    private VultureChatEventFacadeInterface vultureChatEventFacadeInterface;

    @Override
    public void handle(VultureChannel vultureChannel) throws RemoteException {
        boolean isHandShakeConnect = true;
        String accId = null;
        try {
            accId = ChannelAttrs.getAttrs(vultureChannel).getAccId();
        } catch (IllegalStateException illegalStateException) {
            log.error("未握手的连接断开");
            isHandShakeConnect = false;
        }
        if (isHandShakeConnect) {
            // 清理映Netty Vulture射表
            VultureChannelSupport.removeHandShakeChannel(accId);
        }
        // 清理ChannelAttrs
        ChannelAttrs.clean(vultureChannel);
        // 清理用户通道映射表
        VultureChannelSupport.removeVultureChannel(vultureChannel.getChannel());
        if (isHandShakeConnect) {
            // 通知客户端用户下线
            notifyService(accId);
        }
    }

    private void notifyService(String accId) {
        OfflineEventDTO offlineEventDTO = new OfflineEventDTO();
        offlineEventDTO.setAccId(accId);
        vultureChatEventFacadeInterface.offlineEvent(offlineEventDTO);
    }
}
